package com.yiji.fintech.musfinance.common.converter.base;

import com.acooly.core.common.facade.OrderBase;
import com.yiji.fintech.musfinance.common.annotation.Order2Domain2Event;
import com.yiji.fintech.musfinance.common.domain.base.BaseDomain;
import com.yiji.fintech.musfinance.common.eventbus.event.base.BaseEvent;
import com.yiji.fintech.musfinance.common.exception.EmptyObjectException;
import com.yiji.fintech.musfinance.common.exception.Order2EventException;
import com.yiji.fintech.musfinance.common.exception.ParseAnotationException;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单2事件转换器
 * Created by ouwen@yiji.com} on 2017/9/12.
 */
@Slf4j
public abstract class OrderEventBaseConverter {

    /**
     * 获取Domain上注解Event实例
     * @param domain
     * @return
     */
    protected BaseEvent covert2Event(BaseDomain domain){
        Class _class = domain.getClass();
        Order2Domain2Event domainEvent = (Order2Domain2Event)_class.getAnnotation(Order2Domain2Event.class);
        if(domainEvent != null){
            try {
                return (BaseEvent)domainEvent.eventClass().newInstance();
            }catch (Exception e) {
                throw new ParseAnotationException(e.getMessage());
            }
        }
        throw new EmptyObjectException("Domain转换Event异常：未查找到Domain【"+domain.getClass().getName()+"】对应Event");
    }

    public BaseEvent doExcute(OrderBase order){
        log.info("GID【{}}】流水号【{}】开始转换Order【{}】事件开始",order.getGid(),null,order);
        BaseEvent eventBase ;
        try {
            eventBase = doConverter(order);
        } catch (Exception e) {
            log.error("GID【{}}】流水号【{}】Order转换Event失败",order.getGid(),null,e);
            throw new Order2EventException(e.getMessage());
        }
        log.info("GID【{}}】流水号【{}】Order转换后事件Event【{}】",order.getGid(),null,eventBase);
        return eventBase;
    }

    /**
     * order转换event
     * @param order
     * @return
     */
    protected abstract BaseEvent doConverter(OrderBase order);
}
